package com.pan.old.pa.anju;

import com.pan.old.pa.anju.entity.FangInfo;
import com.pan.old.pa.entity.Info;
import com.pan.old.tools.WriteFileCSV;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

public class Anju {
    private EdgeDriver edgeDriver;

    private WriteFileCSV writeFileCSV;


    public Anju() {
    }

    public void start(String url,String fileName){
        this.edgeDriver = new EdgeDriver();
        edgeDriver.navigate().to(url);
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        writeFileCSV = new WriteFileCSV(fileName,true);
        writeFileCSV.append(new FangInfo().getTitleLineStr());
        do {
            List<Info> pageInfos = getPageInfos();
            writeFileCSV.appendData(pageInfos);
            System.out.println("该页数据已经爬完");
        }while(nxtPage());
        close();
        System.out.println(fileName+" 数据已经爬完");
    }
    public void reStart(String url,String fileName){
        this.edgeDriver = new EdgeDriver();
        edgeDriver.navigate().to(url);
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        writeFileCSV = new WriteFileCSV(fileName,true);
        do {
            List<Info> pageInfos = getPageInfos();
            writeFileCSV.appendData(pageInfos);
            System.out.println("该页数据已经爬完");
        }while(nxtPage());
        close();
        System.out.println(fileName+" 数据已经爬完");
    }

    public boolean nxtPage(){

        try {
            Thread.sleep((long) (4000+ Math.random()*5));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        WebElement aNxt;
        try {
            aNxt = edgeDriver.findElement(By.className("aNxt"));
        }catch (NoSuchElementException e){
//            e.printStackTrace();
            return false;
        }
        String nextUrl = aNxt.getAttribute("href");
        //其他迷惑操作
        if (Math.random()>0.7){
            String itemUrl = edgeDriver.findElement(By.className("zu-info")).findElement(By.cssSelector("a")).getAttribute("href");
            edgeDriver.navigate().to(itemUrl);
            try {
                Thread.sleep((long) (3000+ Math.random()*5));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("跳转："+nextUrl);
//        aNxt.click();
        edgeDriver.navigate().to(nextUrl);
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        return true;
    }

    public List<Info> getPageInfos(){
        List<WebElement> itemElements = edgeDriver.findElements(By.className("zu-itemmod"));
        List<Info> result = itemElements.stream()
                .map(itemElement -> this.getItemInfo(itemElement))
                .collect(Collectors.toList());
        return result;
    }

    public Info getItemInfo(WebElement itemElement){
        WebElement infoElement = itemElement.findElement(By.className("zu-info"));
        WebElement titleElement = infoElement.findElement(By.cssSelector("h3")).findElement(By.cssSelector("a"));

        String title = titleElement.getText().replace(",","，");
        String fangUrl = titleElement.getAttribute("href");

        WebElement itemTagElement = infoElement.findElement(By.className("tag"));
        String itemTag = itemTagElement.getText();
        itemTag = itemTag.replace(",","，");
        String[] tags = itemTag.split(" ");
        String[] strs = tags[0].split("\\|");

        String huXing = strs[0];
        String mianJi = strs[1];
        String cengGao = strs[2];
        String zhongJie = "";
        if (tags.length <2){
            zhongJie = "房东";
        }else {
            zhongJie = tags[1].split(" ")[0].substring(1);
        }

        WebElement addressElement = infoElement.findElement(By.cssSelector("address"));
        String address = addressElement.getText().replace(",","，");

        WebElement botTagElement = infoElement.findElement(By.className("bot-tag"));//details-item
        String botTag = botTagElement.getText().replace("\n","").replace(",","，");


        WebElement sideElement = itemElement.findElement(By.className("zu-side"));
        String price = sideElement.findElement(By.cssSelector("b")).getText();

        Info fangInfo = new FangInfo(title,fangUrl,itemTag,huXing,mianJi,cengGao,zhongJie,address,botTag,price);
        return fangInfo;
    }


    public void close(){
        writeFileCSV.close();
        writeFileCSV = null;
        edgeDriver.quit();
    }

}
